import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

// https://vite.dev/config/
export default defineConfig(async (envConfig) => {
  const env = envConfig.mode === 'production' ? { PROD: true } : { PROD: false }
  env.ANALYZE = envConfig.env && envConfig.env.ANALYZE
  const basePlugins = [vue(), vueDevTools()]

  // 动态按需加载 Element Plus 自动导入插件
  try {
    const [{ default: Components }, { ElementPlusResolver }, { default: ElementPlus }] = await Promise.all([
      import('unplugin-vue-components/vite'),
      import('unplugin-vue-components/resolvers'),
      import('unplugin-element-plus/vite')
    ])
    basePlugins.push(
      Components({ dts: true, resolvers: [ElementPlusResolver({ importStyle: 'css' })] }),
      ElementPlus({ useSource: false })
    )
  } catch (err) {
    console.warn('[vite] 按需组件插件未安装，已跳过（运行 yarn add -D unplugin-vue-components unplugin-element-plus 以启用）。' + err)
  }

  // 动态加载可选插件（缺失依赖不影响 dev）
  if (env.PROD || env.ANALYZE) {
    try {
      const [{ visualizer }, viteCompressionMod] = await Promise.all([
        import('rollup-plugin-visualizer'),
        import('vite-plugin-compression')
      ])
      const viteCompression = viteCompressionMod.default
      basePlugins.push(
        viteCompression({ algorithm: 'gzip', ext: '.gz' }),
        viteCompression({ algorithm: 'brotliCompress', ext: '.br' }),
        visualizer({ filename: 'dist/bundle-report.html', open: false, gzipSize: true, brotliSize: true })
      )
    } catch (err) {
      console.warn('[vite] 可选构建插件未安装或加载失败:', err?.message)
    }
  }

  return {
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    build: {
      chunkSizeWarningLimit: 900,
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              if (id.includes('echarts')) return 'echarts'
              if (id.includes('element-plus')) return 'element'
              if (id.includes('vue-router')) return 'vendor-router'
              if (id.includes('pinia')) return 'vendor-pinia'
              return 'vendor'
            }
          }
        }
      }
    },
    resolve: {
      alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) },
    },
    server: {
      port: 3000,
      proxy: { '/api': { target: 'http://localhost:5239', changeOrigin: true } }
    }
  }
})
